//
//  FileManagerCenter1.m
//  TaoBaoDianPu
//
//  Created by ZhuoLaiQiang@Gmail.com on 7/5/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FileManagerCenter.h"



@implementation FileManagerCenter

+ (NSArray *)getDataFromePlist:(NSString*)fileName
{
    BOOL bExists = [FileManagerCenter validateFileWithFileName: fileName];
    if (!bExists)
    {
        NSString *pathOfMainBoundle = [[NSBundle mainBundle] pathForResource: fileName ofType: nil];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        BOOL cExists = [fileManager fileExistsAtPath: pathOfMainBoundle];   
        if (!cExists) {
            return  nil;
        }
        
        NSString *pathOfDocment = [FileManagerCenter getDocmentFilePathWithFileName: fileName];
        NSError *error = nil;
        [fileManager copyItemAtPath: pathOfMainBoundle toPath: pathOfDocment error: &error];
        
        if (error) {
            return  nil;
        }
    }
    NSString *pathFile = [FileManagerCenter getDocmentFilePathWithFileName: fileName];
    NSArray *array = nil;
    array = [[NSArray alloc] initWithContentsOfFile: pathFile];
    
    if (array) {
        return [array autorelease];
    }
    
    return nil;
}

//所有要写入的数据都必须先要放到array中 然后写入
+(BOOL)writedataToPlistWithObject:(NSArray *)array fileName:(NSString *)fileName
{
    [array retain];
    
    NSString *filePaht = [FileManagerCenter getDocmentFilePathWithFileName: fileName];
    BOOL successOrFaile = [array writeToFile: filePaht atomically: YES];
    
    [array release];
    
    return successOrFaile;
}

//通过文件名获取文件的路径
+ (NSString *)getDocmentFilePathWithFileName:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    
    return appFile;
}

//通过一个文件名，验证一个文件是否存在
+ (BOOL)validateFileWithFileName:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *filePath = [FileManagerCenter getDocmentFilePathWithFileName: fileName];
	BOOL bExists = [fileManager fileExistsAtPath: filePath];   
    
    return bExists;
}

@end
